<template>
  <div class="personnel-add">
    <DynamicForm ref="dynamicFormRef" :rulesForm="state.addPersonnelForms" @click="callBack"
                 :rules="state.rulesAddPersonnel"
                 :refresh="state.refresh"/>
  </div>
</template>

<script lang="ts" setup>

import {defineEmits, onMounted, reactive, ref} from 'vue';
import {useRoute} from 'vue-router';

import {ElMessage} from 'element-plus';

import DynamicForm from '@/components/layout/form/dynamic-form.vue'
import {addPersonnelForms, rulesAddPersonnel} from "@/assets/script/monitor/forms/personnel/personnel-form";
import {addCmsPersonnelApi, findByIdApi, findPersonnelBedApi, modifyCmsPersonnelApi} from '@/api/personnel';
import {listFindByBmsConstVoApi} from "@/api/room";
import {listBmsBedApi} from "@/api/bed";

const dynamicFormRef = ref(DynamicForm)
const route = useRoute()

const state = reactive({
  addPersonnelForms: JSON.parse(JSON.stringify(addPersonnelForms)),
  rulesAddPersonnel: rulesAddPersonnel,
  id: null as any,
  refresh: 0 as number
})

const emits = defineEmits<{ (e: 'appClick', data: object): void }>();

onMounted(() => {
  const card = state.addPersonnelForms[0].card
  card.forEach((e: any) => {
    if (!e.line) {
      e[e.name] = null
    }
  })
  listFindByBmsConstVo(['storey', 'floor', 'room'])
})

const callBack = (data: any) => {
  switch (data.type || '') {
    case 'submit':
      // eslint-disable-next-line no-case-declarations
      let params = data.data
      if (params.bedId) {
        params['personnelBed'] = {
          bedId: params.bedId,
          bedName: params.bedIdName,
          roomType: params.roomType[2],
          roomTypeName: params.roomTypeName[2]
        }
      }
      if (!state.id) {
        params['elderlyOrganization'] = {pensionType: 0, payMethod: 1}
        addCmsPersonnel(params)
      } else {
        params['id'] = state.id
        modifyCmsPersonnel(params)
      }
      break
    case 'roomType':
      debugger
      if (data.data?.length === 3) {
        listBmsBed({roomType: data.data[3], bindStatus: 0});
      } else {
        ElMessage.warning('必须选择房间！')
      }
      break
  }
}

const addCmsPersonnel = (params: any) => {
  addCmsPersonnelApi(params).then((data: any) => {
    if (data.code === 0) {
      ElMessage.success('添加成功！')
      state.refresh = Math.random()
      emits('appClick', {type: 'closeTab', data: route.path})
    } else {
      ElMessage.warning('添加失败！')
    }
  })
}

const modifyCmsPersonnel = (params: any) => {
  modifyCmsPersonnelApi(params).then((data: any) => {
    if (data.code === 0) {
      ElMessage.success('修改成功！')
      state.refresh = Math.random()
      emits('appClick', {type: 'closeTab', data: route.path})
    } else {
      ElMessage.warning('修改失败！')
    }
  })
}
const findById = (params: any) => {
  findByIdApi(params).then((data: any) => {
    const card = state.addPersonnelForms[0].card
    card.forEach((e: any) => {
      if (!e.line) {
        e[e.name] = data[e.name]
        if (e.name === 'idCard') {
          e['disabled'] = true
        }
      }
    })
    findPersonnelBed({personnelId: data.id, deleted: 0})
    state.refresh = Math.random()
  })
}

const findPersonnelBed = (params: any) => {
  findPersonnelBedApi(params).then((data: any) => {
    const roomType = state.addPersonnelForms[0].card.find(({name = ''}) => name === 'roomType')
    const bed = state.addPersonnelForms[0].card.find(({name = ''}) => name === 'bedId')
    if (data.bedId) {
      bed['bedId'] = data.bedId
      listBmsBed({roomType: data.bedId, bindStatus: 0})
    }
    const values = []
    roomType?.options?.forEach((children: any) => {
      const floor = children.children;
      floor.forEach((child: any) => {
        const room = child.children.find(({value = ''}) => value === data.roomType);
        if (room) {
          values.push(children.value)
          values.push(child.value)
          values.push(room.value)
        }
      })
    })
    console.log('values', values)
    roomType['roomType'] = values
    state.refresh = Math.random()
  })
}

const listFindByBmsConstVo = (params = [] as any) => {
  listFindByBmsConstVoApi({dictionaryCodeList: params}).then((data: any) => {
    let item = state.addPersonnelForms[0].card.find(({name = ''}) => name === 'roomType')
    if (item) {
      item.options = [] as any
    }
    const storeyList = data.filter((f: any) => f.dictionaryCode === 'storey')
    storeyList?.forEach((e: any) => {
      let storey = {label: e.constName, value: e.constCode, children: [] as any}
      const floorList = data.filter((f: any) => f.parentCode === e.constCode)
      floorList.forEach((r: any) => {
        let floor = {label: r.constName, value: r.constCode, children: [] as any}
        storey.children.push(floor)
        const room = data.filter((f: any) => f.parentCode === r.constCode)
        room.forEach((m: any) => {
          floor.children.push({label: m.constName, value: m.constCode})
        })
      })
      item?.options?.push(storey)
    })
    console.log('addPersonnelForms', state.addPersonnelForms)
    state.refresh = Math.random()

    if (route.query && route.query.id) {
      state.id = route.query.id
      findById({id: state.id})
    }
  })
}

const listBmsBed = (params: any) => {
  listBmsBedApi(params).then((data: any) => {
    let item = state.addPersonnelForms[0].card.find(({name = ''}) => name === 'bedId')
    if (item) {
      item.options = []
    }
    data.forEach((e: any) => {
      item?.options?.push({label: e.name, value: e.id})
    })
  })
}
</script>